package com.financing.platform.service.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.platform.dao.IEmailTemplateDao;
import com.financing.platform.dto.EmailTemplateDTO;
import com.financing.platform.service.IEmailTemplateService;
import com.financing.platform.util.Dict;
import com.financing.platform.vo.EmailTemplateProjectVO;
import com.financing.platform.vo.EmailTemplateUserVO;

@Service("emailTemplateServiceImpl")
public class EmailTemplateServiceImpl extends BaseServiceImpl implements
		IEmailTemplateService {

	@Autowired
	IEmailTemplateDao emailTemplateDao;

	private EmailTemplateDTO queryTemplateByType(String ttype) {
		return emailTemplateDao.queryTemplateByType(ttype);
	}
	
	public Map<String,Object> spliceEmailContent(String ttype, Map<String, Object> param) {
		
		Map<String,Object> result = new HashMap<String,Object>();
		
		// 现根据模板类型获取模板内容
		EmailTemplateDTO template = queryTemplateByType(ttype);
		String content = template.getTcontent();
		String repeatTr = template.getTrepeatTr();
		if (!(content != null && !content.equals(""))) {
			return result;
		}
		
		String mailSubject = template.gettSubject();

		// 循环Map，值填入模板中
		if (param != null) {
			Iterator<String> it = param.keySet().iterator();
			String key = "";
			String value = "";
			while (it.hasNext()) {
				key = it.next();
				value = param.get(key).toString();
				if ((ttype.equals("02") || ttype.equals("03")) && key.equals("userMobile")) {
					value = (value != null && value.length() > 10) ? value.substring(0,3) + "****" + value.substring(7,11) : value;
				}else if ((ttype.equals("05") || ttype.equals("06")) && key.equals("pOrderNum")) {
					value = (value != null && value.length() == 10) ? value.substring(0, 4) + "&nbsp;" + value.substring(4, 8) + "&nbsp;"
							+ value.substring(8, 10) : value;
				}
				content = content.replace("{" + key + "}", value);
				mailSubject = mailSubject.replace("{" + key + "}", value);
			}
			if (repeatTr != null && !repeatTr.equals("")) {
				List<?> list = (List<?>) param.get("list");
				content = content.replace("{dataList}", doRepeatTr(ttype, repeatTr, list));
			}
		}
		
		result.put(Dict.mail_subject, mailSubject);
		result.put(Dict.mail_content, content);
		return result;
	}
	
	/**
	 * 根据传入的模板类型和集合，拼接数据并返回
	 * @param ttype
	 * @param repeatTr
	 * @param list
	 * @return
	 */
	private String doRepeatTr(String ttype, String repeatTr, List<?> list) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		if(ttype != null && repeatTr != null && list != null && !ttype.equals("") && !repeatTr.equals("") && (list.size() > 0)){
			StringBuffer sb = new StringBuffer();
			if(ttype.equals("01")){
				EmailTemplateUserVO user = null;
				for(int i = 0 ;i <list.size();i++){
					user = (EmailTemplateUserVO)list.get(i);
					sb.append(repeatTr
							.replace("{createDate}", user.getCreateTime() != null ? sdf.format(user.getCreateTime()) : "")
							.replace("{userName}", user.getUserName())
							.replace("{userMobile}", user.getUserMobile())
							.replace("{userStatus}", user.getUserStatus()));
				}
			}else if(ttype.equals("02") || ttype.equals("03")){
				EmailTemplateProjectVO project = null;
				for (int i = 0; i < list.size(); i++) {
					project = (EmailTemplateProjectVO)list.get(i);
					sb.append(repeatTr
							.replace("{pInvestType}", project.getProjectInvestType())
							.replace("{pName}", project.getProjectName())
							.replace("{pProfitAmount}", project.getProjectAnnualRevenueExpect())
							.replace("{pPaymentInterestType}", project.getProjectPaymentInterestType())
							.replace("{pDueTime}", project.getProjectDueTime())
							.replace("{pJinDu}", project.getProjectProgress())
							.replace("{pid}", project.getPid())
							.replace("{projectCode}", project.getProjectCode())
							.replace("{marginString}", (i + 1) % 2 != 0 ? "15px 15px 0px 15px":"15px 15px 0px 0px")
							);
				}
			}else if(ttype.equals("04") || ttype.equals("07")){
				EmailTemplateUserVO user = null;
				for (int i = 0; i < list.size(); i++) {
					user = (EmailTemplateUserVO)list.get(i);
					sb.append(repeatTr
							.replace("{createDate}", user.getCreateTime() != null ? sdf.format(user.getCreateTime()) : "")
							.replace("{userName}", user.getUserName())
							.replace("{userMobile}", user.getUserMobile())
							.replace("{yuYueId}", user.getYuYueId())
							.replace("{yuYueName}", user.getYuYueProjectName()));
				}
			}else if(ttype.equals("08")){
				String tmp = "</table><table border='0' cellspacing='0' cellpadding='0' width='720' "
						+ "style='width:720px;border-collapse: collapse; border-color: #000; font-size: 14px; "
						+ "text-align: center;border-spacing: 0;border-collapse: collapse;'>"
						+ "<tr style='height:50px;border-bottom: solid 1px #ccc;'><td width='15' style='width:15px; background-color:#EFEDED;border-bottom: solid 1px #EFEDED;'></td>"
						+ "<td style='width:140px;'>产品名称</td>"
						+ "<td style='width:80px;'>预期年化</td>"
						+ "<td style='width:100px;'>付款方式</td>"
						+ "<td style='width:90px;'>投资期限</td>"
						+ "<td style='width:90px;'>投资领域</td>"
						+ "<td>预约</td>"
						+ "<td width='15' style='width:15px; background-color:#EFEDED;border-bottom: solid 1px #EFEDED;'></td></tr>";
				String repeatTr1 = repeatTr.split(",,,,,")[0];
				String repeatTr2 = repeatTr.split(",,,,,")[1];
				
				EmailTemplateProjectVO project = null;
				for (int i = 0; i < list.size(); i++) {
					project = (EmailTemplateProjectVO)list.get(i);
					if(i < 4){
						sb.append((i % 2 == 0 ? "<tr>" : "") + repeatTr1
								.replace("{pInvestType}", project.getProjectInvestType())
								.replace("{pName}", project.getProjectName())
								.replace("{pProfitAmount}", project.getProjectAnnualRevenueExpect())
								.replace("{pPaymentInterestType}", project.getProjectPaymentInterestType())
								.replace("{pDueTime}", project.getProjectDueTime())
								.replace("{pJinDu}", project.getProjectProgress())
								.replace("{pid}", project.getPid())
								.replace("{projectCode}", project.getProjectCode())
								.replace("{marginString}", (i + 1) % 2 != 0 ? "15px 15px 0px 15px":"15px 15px 0px 0px")
								+ (i % 2 == 1 ? "</tr>" : ""));
					}else {
						if (i == 4) {
							sb.append(tmp);
						}
						sb.append(repeatTr2
								.replace("{pInvestType}", project.getProjectInvestType())
								.replace("{pName}", project.getProjectName())
								.replace("{pProfitAmount}", project.getProjectAnnualRevenueExpect())
								.replace("{pPaymentInterestType}", project.getProjectPaymentInterestType())
								.replace("{pDueTime}", project.getProjectDueTime())
								.replace("{pJinDu}", project.getProjectProgress())
								.replace("{pid}", project.getPid())
								.replace("{projectCode}", project.getProjectCode())
								);
					}
				}
				
			}
			return sb.toString();
		}
		return "";
	}
	
}
